<?php
/**
 * {DB.php}
 *
 * Author: asuslx (asuslx@gmail.com)
 * Date: 8/17/12
 */
 
class MYDB {

    public static function initialize($host, $user, $password, $database) {

        if(!mysql_connect($host, $user, $password)) return false;
        if(!mysql_select_db($database)) return false;
        if(!mysql_query("SET NAMES 'cp1251';")) return false;

        return true;
    }

    // for small queries
    public static function fetch($sql) {

        if(func_num_args() > 1) {
            $sql = self::_formatQuery(func_get_args());
        }
        if(!empty($_GET['_trace']) && $_GET['_trace']=='db') {
            echo $sql.'<br/>';
        }
        if(!$qry = mysql_query($sql)) return false;
        $result = array();
        while($rec = mysql_fetch_assoc($qry)) {$result[] = $rec;}

        return $result;
    }

    private static function _formatQuery($args) {

        $params = array();
        $sql = $args[0];
        for($i = 1; $i < count($args); $i++) {
            if(is_string($args[$i])) $args[$i] = mysql_real_escape_string($args[$i]);
            $params[]=$args[$i];
        }
        eval('$sql = sprintf($sql, "'.implode('","', $params).'");');

        return $sql;
    }

    // returns cursor
    public static function query($sql) {

        if(func_num_args() > 1) {
            $sql = self::_formatQuery(func_get_args());
        }

        if(!empty($_GET['_trace']) && $_GET['_trace']=='db') {
            echo $sql.'<br/>';
        }

        return mysql_query($sql);
    }

    // iterates cursor
    public static function next($cursor) {

        return mysql_fetch_assoc($cursor);
    }

    // for exec statements
    public static function exec($sql) {

        if(func_num_args() > 1) {
            $sql = self::_formatQuery(func_get_args());
        }

        if(!empty($_GET['_trace']) && $_GET['_trace']=='db') {
            echo $sql.'<br/>';
        }
        
        return mysql_query($sql);
    }

    // last error
    public static function lastError() {

        return mysql_error();
    }
}